<template>
  <div class="container">
    <div class="page-head">
      <div class="left">
        <el-form :inline="true" :model="query" @submit.native.prevent>
          <div>
            <el-form-item>
            <picker-view v-model="query.store_id" type="store" :multiple="true" placeholder="门店" />
          </el-form-item>

          <el-form-item>
            <el-input v-model="query.keyword" placeholder="联系人 / 手机号" clearable />
          </el-form-item>
          <el-form-item>
            <picker-view v-model="query.user_id" type="user" :multiple="true" placeholder="销售" />
          </el-form-item>

          <el-form-item>
            <source-picker-view ref="sourcePickerRef" v-model="query.source_id" type="source" placeholder="请选择渠道" />
          </el-form-item>
          </div>
          <div>
            <el-form-item>
            <picker-view v-model="query.brand_id" type="company" placeholder="请选择品牌"></picker-view>
          </el-form-item>
          <el-form-item>
            <el-date-picker v-model="query.sign_date_range" type="daterange" range-separator="至"
              start-placeholder="签单开始日期" end-placeholder="签单结束日期" value-format="yyyy-MM-dd" />
          </el-form-item>
          <el-button type="primary" native-type="submit" @click="doSearch">搜索</el-button>
          </div>

        </el-form>
      </div>

      <!-- 更多搜索 -->
      <div class="right">
        <el-popover placement="bottom" width="500" trigger="click">
          <el-form :model="query" label-width="80px" label-position="right" @submit.native.prevent>

            <el-form-item label="部门">
              <dpt-picker-view ref="dptPickerRef" v-model="query.department_id" type="department" placeholder="请选择部门" />
            </el-form-item>

            <el-form-item label="预产期">
              <el-date-picker v-model="query.event_date_range" type="daterange" range-separator="至"
                start-placeholder="开始日期" end-placeholder="结束日期" value-format="yyyy-MM-dd" />
            </el-form-item>

            <el-form-item>
              <el-button type="primary" @click="doSearch">搜索</el-button>
              <el-button type="warning" @click="doReset">重置</el-button>
            </el-form-item>
          </el-form>
          <el-button slot="reference" type="primary"><i class="el-icon-search"
              style="margin-right: 5px" />更多</el-button>
        </el-popover>
      </div>
    </div>

    <el-table ref="tableView" v-loading="loading" height="tableHeight" class="page-body" :data="tableData" border
      @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="操作" width="100" align="center">
        <template slot-scope="scope">
          <el-link type="primary" @click="showDetailView(scope.row.id)">查看</el-link>
        </template>
      </el-table-column>
      <el-table-column label="门店" prop="bom.store.title" show-overflow-tooltip />
      <el-table-column label="签单销售" prop="user.realname" align="center" />
      <el-table-column label="合同金额" prop="bom.totals" />
      <el-table-column label="创建时间" prop="create_time" />
    </el-table>

    <!-- 分页 -->
    <div class="page-foot">
      <div class="left">
        <el-button v-has="'order-transfer'" type="primary" icon="el-icon-share" @click="showShareView">转单</el-button>
        <el-button v-has="'order-export'" type="primary" icon="el-icon-download" @click="excelFile">导出</el-button>
      </div>
      <div class="right">
        <common-pagination :total="pg.total" :page.sync="pg.page" :limit.sync="pg.limit" @getList="getTableData" />
      </div>
    </div>

    <detail-view ref="detailView" />
    <share-view ref="shareView" @submit="doShare" />
  </div>
</template>

<script>
import {
  getOrderListApi,
  doTransferApi, doExportApi
} from '@/api/order/order'

import {
  getDepartmentTreeApi
} from '@/api/ucenter/department'
import pagination from '@/components/mixins/pagination.vue'
import sourcePickerView from '@/components/picker/source.vue'
import dptPickerView from '@/components/picker/department.vue'
import pickerView from '@/components/picker/select.vue'
import detailView from '../detail/index'
import shareView from '@/components/picker/share.vue'
import dictionary from '@/utils/dictionary'

const query = {
  keyword: '',
  source_id: [],
  store_id: [],
  department_id: '',
  user_id: [],
  sign_date_range: [],
  event_date_range: [],
  brand_id: ""
}

export default {
  components: {
    detailView,
    pickerView,
    sourcePickerView,
    dptPickerView,
    shareView
  },
  provide() {
    return {
      listVue: this
    }
  },
  mixins: [pagination],
  data() {
    return {
      query: Object.assign({}, query),
      loading: false,
      tableData: [],
      departmentTree: []
    }
  },
  created() {
    this.getTableData()
    this.getDptTree()
  },
  methods: {
    doSearch() {
      this.resetPg()
      this.getTableData()
    },
    doReset() {
      this.query = JSON.parse(JSON.stringify(query))
    },
    getTableData() {
      const params = Object.assign({}, this.query)
      params['pagination'] = this.pg
      this.loading = true
      getOrderListApi(params).then((res) => {
        this.loading = false
        this.tableData = res.data.list
        this.setPg(res)
      })
    },
    // 获取Tree数据
    getDptTree() {
      const that = this
      getDepartmentTreeApi().then((res) => {
        that.departmentTree = res.data.tree
      })
    },
    handleCascader(e) {
      const last = e.length - 1
      this.query.department_id = e[last]
    },
    // 显示客资详情
    showDetailView(id) {
      this.$refs['detailView'].showDrawer(id)
    },
    showShareView() {
      if (this.selectedRow.length === 0) {
        this.$message.error('请选择要转交的订单')
        return
      }
      const ids = this.selectedRow.map(item => item.id)
      this.$refs['shareView'].showDialog(ids)
    },
    doShare(userIds) {
      if (userIds.length === 0) {
        this.$message.error('请选择要接收的人')
        return
      }

      if (userIds.length > 1) {
        this.$message.error('一次只能选择一人')
        return
      }

      const options = {}
      const orderIds = this.selectedRow.map(e => e.id)
      options['order_id'] = orderIds
      options['user_id'] = userIds[0]

      doTransferApi(options).then(res => {
        if (res.code == 200) {
          this.$message.success(res.msg)
          this.getTableData()
          this.clearSelection()
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    excelFile() {
      let _this = this;
      if (_this.query.brand_id == '') {
        this.$message.error('请选择品牌');
        return false;
      }
      if (_this.query.sign_date_range.length == 0) {
        this.$message.error('请选择日期时间');
        return false;
      }

      const params = Object.assign({}, this.query)
      params['pagination'] = this.pg
      doExportApi(params).then((res) => {
        if (res.code == '200') {
          let link = document.createElement('a');
          link.href = res.data.url;

          window.open(link.href, 'blank');
          // link.click();

        } else {
          // 提醒
          this.$message.error(res.message)
        }
      })

    },
    doExport() {
      const params = JSON.parse(JSON.stringify(this.query))
      params['is_export'] = 1
      // 获取文件地址并下载
      getOrderListApi(params).then(res => {
        if (res.code == "200") {
          const url = res.data.url
          const link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          document.body.appendChild(link)
          link.click()
        } else {
          // 提醒
          this.$message.error(res.msg)
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.table-list {
  .customer-tag {
    margin-right: 5px;
  }
}

.bottom-box {
  display: flex;
  justify-content: center;
  align-items: center;

  .funcs-box {
    flex: 1;
    text-align: left;

    .func-item {
      margin-right: 8px;
    }
  }

  .pagination-box {
    flex: 1;
    text-align: right;
  }
}
</style>
